package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.OrderService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

@Slf4j
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private UserMapper userMapperl;
    @Autowired
    private WeChatPayUtil weChatPayUtil;

    @Autowired
    private WebSocketServer webSocketServer;

    @Value("${sky.shop.address}")
    private String shopAddress;

    @Value("${sky.baidu.ak}")
    private String ak;

    /**
     * 下单接口
     *
     * @param dto
     * @return
     */
    @Transactional
    @Override
    public Result submit(OrdersSubmitDTO dto) {
        //判断收货地址是否为空
        AddressBook addressBook = addressBookMapper.getById(dto.getAddressBookId());
        if (addressBook == null) {
            return Result.error(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        //检查地址是否在配送范围
        checkOutOfRange(addressBook.getCityName() + addressBook.getDistrictName() + addressBook.getDetail());
        //判断购物车地址是否为空
        List<ShoppingCart> cartList = shoppingCartMapper.getByUserId(BaseContext.getCurrentId());
        if (cartList.size() == 0 || cartList == null) {
            return Result.error(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        //插入订单数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(dto, orders);
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getDetail());
        orders.setConsignee(addressBook.getConsignee());
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setUserId(BaseContext.getCurrentId());
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setPayStatus(Orders.UN_PAID);
        orders.setOrderTime(LocalDateTime.now());
        orderMapper.addOrders(orders);
        //插入订单明细数据
        List<OrderDetail> orderDetailList = new ArrayList<>();
        cartList.forEach(shoppingCart -> {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart, orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);
        });
        orderDetailMapper.addList(orderDetailList);
        //清空购物车
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(BaseContext.getCurrentId());
        shoppingCartMapper.clean(shoppingCart);
        OrderSubmitVO vo = new OrderSubmitVO().builder()
                .id(orders.getId())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .orderTime(LocalDateTime.now())
                .build();

        return Result.success(vo);
    }

    /**
     * 查看历史订单
     *
     * @return
     */
    @Override
    public Result list(OrdersPageQueryDTO dto) {
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        Page<OrderVO> voList = orderMapper.page(dto);
        if (voList.size() == 0 || voList == null) {
            return Result.success(MessageConstant.ORDER_NOT_FOUND);
        }
        voList.forEach(orderVO -> {
            List<OrderDetail> byOrderId = orderDetailMapper.getByOrderId(orderVO.getId());
            orderVO.setOrderDetailList(byOrderId);

        });

        return Result.success(new PageResult(voList.getTotal(), voList.getResult()));
    }

    /**
     * 查询订单
     *
     * @param id
     * @return
     */
    @Override
    public Result orderDetail(Long id) {
        OrderVO orderVO = orderMapper.query(id);
        if (orderVO == null) {
            return Result.error(MessageConstant.ORDER_NOT_FOUND);

        }
        List<OrderDetail> byOrderId = orderDetailMapper.getByOrderId(id);
        orderVO.setOrderDetailList(byOrderId);
        return Result.success(orderVO);
    }

    /**
     * 再来一单
     *
     * @param id
     * @return
     */
    @Transactional
    @Override
    public Result repetition(Long id) {

        List<OrderDetail> detailList = orderDetailMapper.getByOrderId(id);
        if (detailList != null) {
            detailList.forEach(orderDetail -> {
                orderDetail.setId(null);
                ShoppingCart shoppingCart = new ShoppingCart();
                BeanUtils.copyProperties(orderDetail, shoppingCart);
                shoppingCart.setUserId(BaseContext.getCurrentId());
                shoppingCart.setCreateTime(LocalDateTime.now());


                shoppingCartMapper.insert(shoppingCart);
            });
        }
        return Result.success();
    }

    /**
     * 取消订单
     *
     * @param id
     * @return
     */
    @Transactional
    @Override
    public Result cancel(Long id) {
        orderMapper.cancel(id);
        return Result.success();
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapperl.getById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = orderMapper.getByNumberAndUserId(outTradeNo, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);
    }

    /**
     * 管理端订单分页显示
     *
     * @param dto
     * @return
     */
    @Override
    public Result page(OrdersPageQueryDTO dto) {
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        Page<OrderVO> voList = orderMapper.page(dto);
        if (voList.size() > 0 && voList != null) {
            voList.forEach(orderVO -> {
                List<OrderDetail> byOrderId = orderDetailMapper.getByOrderId(orderVO.getId());
                orderVO.setOrderDetailList(byOrderId);
                List<String> list = new ArrayList<>();
                byOrderId.forEach(orderDetail -> {
                    list.add(orderDetail.getName() + "x" + orderDetail.getNumber());
                });
                String name = list.toString();
                String replace = name.replace("[", "").replace("]", "");
                orderVO.setOrderDishes(replace);
            });
        }
        return Result.success(new PageResult(voList.getTotal(), voList.getResult()));
    }

    /**
     * 统计各个状态订单个数
     *
     * @param
     * @return
     */
    @Override
    public Result count() {
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        System.out.println(orderMapper.count(Orders.TO_BE_CONFIRMED));
        orderStatisticsVO.setToBeConfirmed(orderMapper.count(Orders.TO_BE_CONFIRMED));
        orderStatisticsVO.setConfirmed(orderMapper.count(Orders.CONFIRMED));
        System.out.println(orderMapper.count(Orders.CONFIRMED));
        orderStatisticsVO.setDeliveryInProgress(orderMapper.count(Orders.DELIVERY_IN_PROGRESS));
        System.out.println(orderMapper.count(Orders.DELIVERY_IN_PROGRESS));
        return Result.success(orderStatisticsVO);
    }

    /**
     * 后台取消订单接口
     *
     * @param dto
     * @return
     */
    @Transactional
    @Override
    public Result adminCancel(OrdersCancelDTO dto) {
        if (dto.getCancelReason() == null) {
            return Result.error("取消原因不能为空");

        }
        OrderVO query = orderMapper.query(dto.getId());
        if (query.getStatus() == Orders.COMPLETED) {
            return Result.error("已经完成的订单不能取消");

        }
        Orders orders = new Orders().builder()
                .cancelReason(dto.getCancelReason())
                .cancelTime(LocalDateTime.now())
                .status(Orders.CANCELLED)
                .id(dto.getId())
                .payStatus(2)
                .build();
        orderMapper.update(orders);
        //退款   TODO
        return Result.success();
    }

    /**
     * 据单
     *
     * @param dto
     * @return
     */
    @Transactional
    @Override
    public Result rejection(OrdersRejectionDTO dto) {
        Orders orders = new Orders().builder()
                .rejectionReason(dto.getRejectionReason())
                .status(Orders.CANCELLED)
                .cancelTime(LocalDateTime.now())
                .id(dto.getId())
                .payStatus(2)
                .build();
        orderMapper.update(orders);
        //退款   TODO
        return Result.success();
    }

    /**
     * 接单
     *
     * @param dto
     * @return
     */
    @Transactional
    @Override
    public Result confirm(OrdersConfirmDTO dto) {
        Orders orders = new Orders().builder()
                .status(Orders.CONFIRMED)
                .id(dto.getId())
                .build();
        orderMapper.update(orders);

        return Result.success();
    }

    /**
     * 订单派送
     *
     * @param id
     * @return
     */
    @Override
    public Result delivery(Long id) {
        Orders orders = new Orders();
        orders.setId(id);
        // 更新订单状态,状态转为派送中
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);



        orderMapper.update(orders);

        return Result.success();
    }

    /**
     * 完成订单
     *
     * @param id
     * @return
     */
    @Transactional
    @Override
    public Result complete(Long id) {
        Orders orders = new Orders();
        orders.setId(id);
        orders.setStatus(Orders.COMPLETED);
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setDeliveryTime(LocalDateTime.now());
        orderMapper.update(orders);
        return Result.success();
    }

    /**
     * 用户催单
     *
     * @param id
     * @return
     */
    @Override
    public void reminder(Long id) {
        // 查询订单是否存在
        OrderVO orders = orderMapper.query(id);
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        //基于WebSocket实现催单
        Map map = new HashMap();
        map.put("type", 2);//2代表用户催单
        map.put("orderId", id);
        map.put("content", "订单号：" + orders.getNumber());
        webSocketServer.sendToAllClient(JSON.toJSONString(map));


    }

    /**
     * 检查客户的收货地址是否超出配送范围
     *
     * @param address
     */
    private void checkOutOfRange(String address) {
        Map map = new HashMap();
        map.put("address", shopAddress);
        map.put("output", "json");
        map.put("ak", ak);
        //获取店铺的经纬度坐标
        //url https://api.map.baidu.com/geocoding/v3/?address=北京市海淀区上地十街10号&output=json&ak=您的ak&callback=showLocation //GET请求
        /*
         * 需要参数地址 address 地址
         *            output json
         *               ak ak
         * */
        String shopCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);
        JSONObject jsonObject = JSON.parseObject(shopCoordinate);
        if (!jsonObject.get("status").equals(0)) {
            throw new OrderBusinessException("店铺地址解析失败");
        }
        //getJSONObject()获取JSON字符串中的键值转返回一个新的JSON字符串
        JSONObject location = jsonObject.getJSONObject("result").getJSONObject("location");
        String lat = location.getString("lat");//获取可以中的值返回字符串  经纬
        String lng = location.getString("lng");//获取可以中的值返回字符串 纬度
        //店铺经纬度坐标
        String shopLngLat = lat + "," + lng;
        log.info("店铺经纬度坐标", shopLngLat);
        map.put("address", address);
        //获取用户收货地址的经纬度坐标
        String userCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);
        JSONObject parseObject = JSON.parseObject(userCoordinate);
        if (!parseObject.get("status").equals(0)) {
            throw new OrderBusinessException("收货地址解析失败");
        }
        location = parseObject.getJSONObject("result").getJSONObject("location");
        lat = location.getString("lat");//获取可以中的值返回字符串  经纬
        lng = location.getString("lng");//获取可以中的值返回字符串 纬度
        //用户收货地址经纬度坐标
        String userLngLat = lat + "," + lng;
        log.info("用户收货地址经纬度坐标", userLngLat);
        //路线规划URL https://api.map.baidu.com/directionlite/v1/driving?origin=40.01116,116.339303&destination=39.936404,116.452562&ak=您的AK  //GET请求
        /*请求参数
        origin 起点
        destination 终点
        steps_info
        ak
        * */

        map.put("origin", shopLngLat);
        map.put("destination", userLngLat);
        map.put("steps_info", "0");
        //路线规划
        String json = HttpClientUtil.doGet("https://api.map.baidu.com/directionlite/v1/driving", map);
        //数据解析
        JSONObject object = JSON.parseObject(json);
        if (!object.get("status").equals(0)) {
            throw new OrderBusinessException("路线规划失败");
        }
        //数据解析
        JSONObject result = object.getJSONObject("result");
        JSONArray jsonArray = (JSONArray) result.get("routes");
        Integer distance = (Integer) ((JSONObject) jsonArray.get(0)).get("distance");
        log.info("方案距离distance:", distance);
        if (distance > 5000) {
            //配送距离超过5000米
            throw new OrderBusinessException("超出配送范围");

        }

    }
}
